// 高德地图工具类
const AMAP_KEY = 'a8823ccf8b8e91be6a767661582a22a2'

/**
 * 初始化高德地图
 * @param {string} containerId - 地图容器ID
 * @param {Object} options - 地图配置选项
 * @returns {Promise<AMap.Map>} 地图实例
 */
export const initAMap = (containerId, options = {}) => {
  return new Promise((resolve, reject) => {
    if (!window.AMap) {
      reject(new Error('高德地图API未加载'))
      return
    }

    const defaultOptions = {
      zoom: 11,
      center: [116.397428, 39.90923], // 北京市中心
      viewMode: '3D',
      pitch: 0,
      ...options
    }

    try {
      const map = new AMap.Map(containerId, defaultOptions)
      resolve(map)
    } catch (error) {
      reject(error)
    }
  })
}

/**
 * 获取用户当前位置
 * @param {boolean} useMock - 是否使用模拟定位
 * @returns {Promise<Object>} 位置信息
 */
export const getCurrentPosition = (useMock = false) => {
  return new Promise((resolve, reject) => {
    // 如果使用模拟定位或高德地图API未加载
    if (useMock || !window.AMap) {
      setTimeout(() => {
        // 模拟北京市中心附近的随机位置
        const mockPosition = {
          lng: 116.397428 + (Math.random() - 0.5) * 0.02,
          lat: 39.90923 + (Math.random() - 0.5) * 0.02,
          address: '北京市朝阳区建国门外大街1号（模拟地址）',
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          street: '建国门外大街',
          streetNumber: '1号'
        }
        resolve(mockPosition)
      }, 1000)
      return
    }

    AMap.plugin('AMap.Geolocation', () => {
      const geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 0,
        convert: true,
        showButton: false,
        buttonPosition: 'LB',
        buttonOffset: new AMap.Pixel(10, 20),
        showMarker: false,
        showCircle: false,
        panToLocation: false,
        zoomToAccuracy: false
      })

      geolocation.getCurrentPosition((status, result) => {
        if (status === 'complete') {
          resolve({
            lng: result.position.lng,
            lat: result.position.lat,
            address: result.formattedAddress,
            province: result.addressComponent.province,
            city: result.addressComponent.city,
            district: result.addressComponent.district,
            street: result.addressComponent.street,
            streetNumber: result.addressComponent.streetNumber
          })
        } else {
          // 定位失败时使用模拟定位
          console.warn('高德定位失败，使用模拟定位:', result.message)
          const mockPosition = {
            lng: 116.397428 + (Math.random() - 0.5) * 0.02,
            lat: 39.90923 + (Math.random() - 0.5) * 0.02,
            address: '北京市朝阳区建国门外大街1号（模拟地址）',
            province: '北京市',
            city: '北京市',
            district: '朝阳区',
            street: '建国门外大街',
            streetNumber: '1号'
          }
          resolve(mockPosition)
        }
      })
    })
  })
}

/**
 * 地理编码 - 地址转坐标
 * @param {string} address - 地址
 * @returns {Promise<Object>} 坐标信息
 */
export const geocode = (address) => {
  return new Promise((resolve, reject) => {
    if (!window.AMap) {
      reject(new Error('高德地图API未加载'))
      return
    }

    AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new AMap.Geocoder({
        city: '010' // 城市设为北京，用于提高精确度
      })

      geocoder.getLocation(address, (status, result) => {
        if (status === 'complete' && result.geocodes.length) {
          const location = result.geocodes[0]
          resolve({
            lng: location.location.lng,
            lat: location.location.lat,
            address: location.formattedAddress,
            level: location.level
          })
        } else {
          reject(new Error('地址解析失败'))
        }
      })
    })
  })
}

/**
 * 逆地理编码 - 坐标转地址
 * @param {number} lng - 经度
 * @param {number} lat - 纬度
 * @returns {Promise<Object>} 地址信息
 */
export const reverseGeocode = (lng, lat) => {
  return new Promise((resolve, reject) => {
    if (!window.AMap) {
      reject(new Error('高德地图API未加载'))
      return
    }

    AMap.plugin('AMap.Geocoder', () => {
      const geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: 'all'
      })

      geocoder.getAddress([lng, lat], (status, result) => {
        if (status === 'complete' && result.regeocode) {
          const regeocode = result.regeocode
          resolve({
            address: regeocode.formattedAddress,
            province: regeocode.addressComponent.province,
            city: regeocode.addressComponent.city,
            district: regeocode.addressComponent.district,
            street: regeocode.addressComponent.street,
            streetNumber: regeocode.addressComponent.streetNumber,
            adcode: regeocode.addressComponent.adcode
          })
        } else {
          reject(new Error('坐标解析失败'))
        }
      })
    })
  })
}

/**
 * 搜索地点
 * @param {string} keyword - 搜索关键词
 * @param {Object} options - 搜索选项
 * @returns {Promise<Array>} 搜索结果
 */
export const searchPlace = (keyword, options = {}) => {
  return new Promise((resolve, reject) => {
    if (!window.AMap) {
      reject(new Error('高德地图API未加载'))
      return
    }

    AMap.plugin('AMap.PlaceSearch', () => {
      const placeSearch = new AMap.PlaceSearch({
        city: options.city || '010', // 默认北京
        citylimit: options.citylimit || true,
        pageSize: options.pageSize || 10,
        pageIndex: options.pageIndex || 1,
        extensions: 'all'
      })

      placeSearch.search(keyword, (status, result) => {
        if (status === 'complete' && result.poiList && result.poiList.pois) {
          const pois = result.poiList.pois.map(poi => ({
            id: poi.id,
            name: poi.name,
            address: poi.address,
            location: {
              lng: poi.location.lng,
              lat: poi.location.lat
            },
            type: poi.type,
            tel: poi.tel,
            distance: poi.distance
          }))
          resolve(pois)
        } else {
          reject(new Error('搜索失败'))
        }
      })
    })
  })
}

/**
 * 计算两点间距离
 * @param {Object} point1 - 起点 {lng, lat}
 * @param {Object} point2 - 终点 {lng, lat}
 * @returns {number} 距离（米）
 */
export const calculateDistance = (point1, point2) => {
  if (!window.AMap) {
    throw new Error('高德地图API未加载')
  }

  const p1 = new AMap.LngLat(point1.lng, point1.lat)
  const p2 = new AMap.LngLat(point2.lng, point2.lat)
  return p1.distance(p2)
}

/**
 * 在地图上添加标记
 * @param {AMap.Map} map - 地图实例
 * @param {Object} position - 位置 {lng, lat}
 * @param {Object} options - 标记选项
 * @returns {AMap.Marker} 标记实例
 */
export const addMarker = (map, position, options = {}) => {
  if (!window.AMap) {
    throw new Error('高德地图API未加载')
  }

  const defaultOptions = {
    position: [position.lng, position.lat],
    title: options.title || '',
    ...options
  }

  const marker = new AMap.Marker(defaultOptions)
  marker.setMap(map)
  return marker
}

/**
 * 在地图上添加信息窗体
 * @param {AMap.Map} map - 地图实例
 * @param {Object} position - 位置 {lng, lat}
 * @param {string} content - 内容
 * @param {Object} options - 选项
 * @returns {AMap.InfoWindow} 信息窗体实例
 */
export const addInfoWindow = (map, position, content, options = {}) => {
  if (!window.AMap) {
    throw new Error('高德地图API未加载')
  }

  const defaultOptions = {
    content: content,
    ...options
  }

  const infoWindow = new AMap.InfoWindow(defaultOptions)
  infoWindow.open(map, [position.lng, position.lat])
  return infoWindow
}

export default {
  initAMap,
  getCurrentPosition,
  geocode,
  reverseGeocode,
  searchPlace,
  calculateDistance,
  addMarker,
  addInfoWindow
}